/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "BulletPhysicsDirector.h"
#include "../Managers/BulletPhysicsManager.h"
#include "../Components/RigidBody.h"
#include "../Components/TriggerVolume.h"
#include "../Components/CollisionShape.h"
#include "../Messages/CollisionMessage.h"
#include "../DataStructures/HogsheadRayResultCallback.h"
#include "../DataStructures/HogsheadContactResultCallback.h"
#include "btBulletCollisionCommon.h"
#include "btBulletDynamicsCommon.h"

namespace Hogshead
{
	namespace BulletPhysics
	{
		DirectorCPP(Hogshead::BulletPhysics::BulletPhysicsDirector);

		BulletPhysicsDirector::BulletPhysicsDirector()
		{
			_debug_drawer = NULL;
			_collision_object_index = new HashTable<void*, ICollisionObject*>();
			// set up our world
			_broadphase = new btDbvtBroadphase();
			_collision_configuration = new btDefaultCollisionConfiguration();
			_dispatcher = new btCollisionDispatcher(_collision_configuration);
			_constraint_solver = new btSequentialImpulseConstraintSolver();

			
			
			_dynamics_world = new btDiscreteDynamicsWorld(_dispatcher, _broadphase, _constraint_solver, _collision_configuration);
			
			_dynamics_world->getSolverInfo().m_splitImpulse = true;	// reduce bounciness
			_dynamics_world->setGravity(btVector3(0,0,0));
			// for terminal velocity and other awesomeness (we make it happen before the tick happens to avoid jittering)
			_dynamics_world->setInternalTickCallback(BulletPhysicsManager::preTickCallback, NULL, true);
			_dynamics_world->setInternalTickCallback(BulletPhysicsManager::postTickCallback, NULL, false);
			_gravity.set(0,0,0);
			_pf.registerVariable(ParameterField::Vector3, "gravity", &_gravity);

		}

		BulletPhysicsDirector::~BulletPhysicsDirector()
		{
			delete _collision_object_index;
			delete _broadphase;
			delete _collision_configuration;
			delete _dispatcher;
			delete _constraint_solver;
			delete _dynamics_world;
		}

		void BulletPhysicsDirector::initialize()
		{
			_dynamics_world->setGravity(_gravity);
			_index_enumerator = &(_collision_object_index->getEnumerator());

			BulletPhysicsManager::_dynamics_world_to_director_index->add(_dynamics_world, this);
		}

		void BulletPhysicsDirector::finalize()
		{
			_dynamics_world->setGravity(btVector3(0,0,0));
			if(_debug_drawer)
				delete _debug_drawer;
			_debug_drawer = NULL;
		}
		IDirector* BulletPhysicsDirector::readXML(const String& in_xml)
		{
			IDirector::readXML(in_xml);
			return this;
		}

		void BulletPhysicsDirector::update(const GameTimer& in_gt)
		{
			// update the world
			_dynamics_world->stepSimulation(in_gt.getUpdateDelta(), 10, 1.0f / 120.0f);
			if(in_gt.isDrawCycle())
			{
				_dynamics_world->debugDrawWorld();
			}

			// send collision messages

			int manifold_count = _dispatcher->getNumManifolds();

			for(int k = 0; k < manifold_count; k++)
			{
				btPersistentManifold* contactManifold = _dispatcher->getManifoldByIndexInternal(k);

				int contacts = contactManifold->getNumContacts();
				if(contacts > 0)
				{
					btCollisionObject* obA = (btCollisionObject*)contactManifold->getBody0();
					btCollisionObject* obB = (btCollisionObject*)contactManifold->getBody1();
					ICollisionObject* compA = NULL;
					ICollisionObject* compB = NULL;

					if(_collision_object_index->tryGetValue(obA, compA) && _collision_object_index->tryGetValue(obB, compB))
					{
						CollisionMessage* cmA = Factory::acquire<CollisionMessage>();
						cmA->collided_with = compB;
						
						CollisionMessage* cmB = Factory::acquire<CollisionMessage>();
						cmB->collided_with = compA;

						for(int j = 0; j < contacts; j++)
						{
							
							btManifoldPoint& pt = contactManifold->getContactPoint(j);
							pt.m_normalWorldOnB;
							
							cmA->their_collision_normal = pt.m_normalWorldOnB;
							cmA->my_collision_points.add(pt.getPositionWorldOnA());
							cmA->their_collision_points.add(pt.getPositionWorldOnB());

							cmB->my_collision_points.add(pt.getPositionWorldOnB());
							cmB->their_collision_points.add(pt.getPositionWorldOnA());
							cmB->their_collision_normal = -pt.m_normalWorldOnB;
						}

						compA->sendMessage(cmA);
						compB->sendMessage(cmB);
					}
				}
			}

		}

		void BulletPhysicsDirector::addCollisionObject(ICollisionObject* in_body, short group, short mask)
		{
			
			if(RigidBody* rb = in_body->as<RigidBody>())
			{
				_collision_object_index->add(rb->_rigid_body, rb);
				_dynamics_world->addRigidBody(rb->_rigid_body, group, mask);
				return;
			}
			else if(TriggerVolume* cv = in_body->as<TriggerVolume>())
			{
				_collision_object_index->add(cv->_collision_object, cv);
				_dynamics_world->addCollisionObject(cv->_collision_object, group, mask);
				return;
			}
		}

		void BulletPhysicsDirector::removeCollisionObject(ICollisionObject* in_body)
		{
			if(RigidBody* rb = in_body->as<RigidBody>())
			{
				_dynamics_world->removeRigidBody(rb->_rigid_body);
				_collision_object_index->remove(rb->_rigid_body);
			}
			else if(TriggerVolume* cv = in_body->as<TriggerVolume>())
			{
				_dynamics_world->removeCollisionObject(cv->_collision_object);
				_collision_object_index->remove(cv->_collision_object);
			}
		}

		void BulletPhysicsDirector::setIDebugDraw(btIDebugDraw* in_drawer)
		{
			_dynamics_world->setDebugDrawer(in_drawer);
			_debug_drawer = in_drawer;
		}

		RayCastResults* BulletPhysicsDirector::rayTest(const Vector3& in_from, const Vector3& in_to, unsigned short in_group, unsigned short in_mask) const
		{
			HogsheadRayResultCallback callback;
				callback.m_collisionFilterGroup = in_group;
				callback.m_collisionFilterMask = in_mask;
				callback._from = in_from;
				callback._to = in_to;
				callback._director = this;
				callback._ray_length = (in_to - in_from).getMagnitude();
			//callback.
			//hout << "Raycasting:" << endl;
			_dynamics_world->rayTest(in_from, in_to, callback);

			if(callback._game_objects.size())
			{
				float max = 0.0f;
				RayCastResults* results = new RayCastResults(callback._game_objects.size());
				for(int k = 0; k < results->count; k++)
				{
					Tuple<GameObject*, Vector3, Vector3, float>& t = callback._game_objects[k];
						results->game_object[k] = t.item1;
						results->contact_point[k] = t.item2;
						results->normal[k] = t.item3;
						results->distances[k] = t.item4;
				}
				return results;
			}
			return NULL;
		}

		ContactResults* BulletPhysicsDirector::contactTest(RigidBody* rb) const
		{
			HogsheadContactResultCallback callback;
				callback.m_collisionFilterGroup = rb->_group;
				callback.m_collisionFilterMask = rb->_mask;
				callback._query_body = rb->_rigid_body;
				callback._director = this;
			
			if(rb->_type == RigidBodyType::Kinematic)
			{
				rb->_rigid_body->getMotionState()->getWorldTransform(rb->_rigid_body->getWorldTransform());
				_dynamics_world->updateSingleAabb(rb->_rigid_body);
			}
			_dynamics_world->contactTest(rb->_rigid_body, callback);

			if(callback._game_objects.size())
			{
				ContactResults* results = new ContactResults(callback._game_objects.size());
				for(int k = 0; k < results->count; k++)
				{
					results->game_object[k] = callback._game_objects[k];
					results->their_normals[k] = callback._their_normals[k];
					results->their_contacts[k] = callback._their_contact[k];
					results->my_contacts[k] = callback._my_contact[k];
				}
				return results;
			}
			return NULL;
		}

		ContactResults* BulletPhysicsDirector::contactTest(RigidBody* rb, unsigned short group, unsigned short mask) const
		{
			HogsheadContactResultCallback callback;
				callback.m_collisionFilterGroup = group;
				callback.m_collisionFilterMask = mask;
				callback._query_body = rb->_rigid_body;
				callback._director = this;
			
			if(rb->_type == RigidBodyType::Kinematic)
			{
				rb->_rigid_body->getMotionState()->getWorldTransform(rb->_rigid_body->getWorldTransform());
				_dynamics_world->updateSingleAabb(rb->_rigid_body);
			}
			_dynamics_world->contactTest(rb->_rigid_body, callback);

			if(callback._game_objects.size())
			{
				ContactResults* results = new ContactResults(callback._game_objects.size());
				for(int k = 0; k < results->count; k++)
				{
					results->game_object[k] = callback._game_objects[k];
					results->their_normals[k] = callback._their_normals[k];
					results->their_contacts[k] = callback._their_contact[k];
					results->my_contacts[k] = callback._my_contact[k];
				}
				return results;
			}
			return NULL;
		}

		void BulletPhysicsDirector::getExtents(Vector3& in_mins, Vector3& in_maxs) const
		{
			in_mins.set(Float::Infinity, Float::Infinity, Float::Infinity);
			in_maxs.set(Float::NegativeInfinity, Float::NegativeInfinity, Float::NegativeInfinity);

			btVector3 min(Float::Infinity, Float::Infinity, Float::Infinity);
			btVector3 max(Float::NegativeInfinity, Float::NegativeInfinity,Float::NegativeInfinity);

			_index_enumerator->reset();
			while(_index_enumerator->moveNext())
			{
				Pair<void*, Hogshead::BulletPhysics::ICollisionObject*>& pair = _index_enumerator->current();
				if(pair.second->is<RigidBody>())
				{
					if(((RigidBody*)pair.second)->_type == RigidBodyType::Static)
					{
						btRigidBody* rb = (btRigidBody*)pair.first;
						float margin = rb->getCollisionShape()->getMargin();
						rb->getAabb(min, max);
						in_mins.x = Math::min(in_mins.x, min.x() + margin);
						in_mins.y = Math::min(in_mins.y, min.y() + margin);
						in_mins.z = Math::min(in_mins.z, min.z() + margin);

						in_maxs.x = Math::max(in_maxs.x, max.x() - margin);
						in_maxs.y = Math::max(in_maxs.y, max.y() - margin);
						in_maxs.z = Math::max(in_maxs.z, max.z() - margin);
					}
				}
			}

			/*
			btVector3 mins, maxs;
			_broadphase->getBroadphaseAabb(mins, maxs);
			in_mins = mins;
			in_maxs = maxs;
			*/
		}

	}
}